import requests
import datetime
import hashlib
import hmac
import base64
import mimetypes


def upload_file_to_oss_nosdk(
        access_key_id: str,
        access_key_secret: str,
        bucket_name: str,
        endpoint: str,  # e.g. "oss-cn-shenzhen.aliyuncs.com"
        object_name: str,  # OSS 上的路径/文件名
        file_path: str
) -> None:
    """
    通过 OSS 的 REST 接口，签名并 PUT 上传文件。
    """
    # 1. 读取文件
    with open(file_path, 'rb') as f:
        body = f.read()

    # 2. 计算 Content-MD5（可选，但推荐）
    md5 = hashlib.md5(body).digest()
    content_md5 = base64.b64encode(md5).decode('utf-8')

    # 3. 确定 Content-Type
    content_type, _ = mimetypes.guess_type(file_path)
    if content_type is None:
        content_type = 'application/octet-stream'

    # 4. 格式化当前 GMT 时间
    now = datetime.datetime.utcnow()
    date_str = now.strftime('%a, %d %b %Y %H:%M:%S GMT')

    # 5. 构造签名字符串（无额外 x-oss-meta）
    method = 'PUT'
    canonicalized_oss_headers = ''
    canonicalized_resource = f'/{bucket_name}/{object_name}'
    string_to_sign = '\n'.join([
        method,
        content_md5,
        content_type,
        date_str,
        canonicalized_oss_headers + canonicalized_resource
    ])

    # 6. 计算签名
    h = hmac.new(access_key_secret.encode('utf-8'),
                 string_to_sign.encode('utf-8'),
                 hashlib.sha1)
    signature = base64.b64encode(h.digest()).decode('utf-8')

    # 7. 构造请求 URL & headers
    url = f'https://{bucket_name}.{endpoint}/{object_name}'
    headers = {
        'Content-MD5': content_md5,
        'Content-Type': content_type,
        'Date': date_str,
        'Authorization': f'OSS {access_key_id}:{signature}'
    }

    # 8. 发起 PUT 请求
    resp = requests.put(url, headers=headers, data=body)
    resp.raise_for_status()

    print(f"文件已上传至 OSS: {object_name}")
